﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataLayer;
using DataLayer.Model.Objects;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System.Runtime.Serialization;

namespace BuisnessLayer
{
    public class ProfileReader
    {
        public static IList<Profile> ReadProfiles(){
            var profiles = new List<Profile>();
            var profileNames = Directory.GetFiles(Singleton.Settings.Folders.Profiles);
            foreach(var file in profileNames){
                profiles.Add(ReadProfile(file));
            }
            return profiles;
        }

        private static Profile ReadProfile(string pProfileName)
        {
            try
            {

                var fs = new FileStream(pProfileName,FileMode.Open);
                var reader =
                    XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                var ser = new NetDataContractSerializer();

                // Deserialize the data and read it from the instance.
                var profile = (Profile)ser.ReadObject(reader, true);
                fs.Close();
                return profile;
            }
            catch (Exception ex)
            {
                //TODO: Think out method to handle error
                throw ex ;
            }
        }


        internal static bool ProfileExists(string pProfileName)
        {
            var files = Directory.GetFiles(Singleton.Settings.Folders.Profiles);
            var profiles = new List<string>();

            foreach(var file in files)
                profiles.Add(Path.GetFileNameWithoutExtension(file));

            foreach (var profile in profiles)
                if (profile.Equals(pProfileName))
                    return true;
            return false;
        }
    }
}
